﻿//using Microsoft.AspNet.Hosting;
//using Microsoft.AspNet.Identity;
//using Microsoft.AspNet.Identity.EntityFramework;
//using Microsoft.Data.Entity;
//using Microsoft.Extensions.Caching.Distributed;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Logging;
//using Microsoft.Extensions.PlatformAbstractions;
//using Sino.CapacityCloud.Infrastructure.Events;
//using Sino.CapacityCloud.Infrastructure.Services;
//using Sino.CapacityCloud.Services;
//using Sino.CapacityCloud.Services.Models;
//using Sino.CommonServices.MessageTypes;
//using Sino.TMSystem;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Security.Claims;
//using System.Threading.Tasks;

//namespace Sino.CapacityCloud.Services
//{

//    /// <summary>
//    /// Sync data from TMS server to this App server.
//    /// </summary>
//    public class TmsSyncOrderBackgroundWorker
//        : BackgroundWorker, ITmsSyncOrderBackgroundWorker
//    {

//        public const string ConfigurationFileName = "appsettings";

//        private static int InstanceCount = 0;

//        private readonly IDistributedCache _cache;
//        private readonly ITmsServiceBus _tmsServiceBus;
//        private readonly IServiceProvider _serviceProvider;
//        private readonly IBankCardService _bankCard;

//        public IConfiguration Configuration { get; }

//        public string DomainName { get; }

//        public TmsSyncOrderBackgroundWorker(
//            ILoggerFactory loggerFactory,
//            IApplicationEnvironment appEnv,
//            IHostingEnvironment env,
//            ITmsServiceBus tmsServiceBus,
//            IDistributedCache cache,
//            IBankCardService bankCard,
//            IServiceProvider serviceProvider)
//            : base(loggerFactory)
//        {
//            this._cache = cache;
//            this._bankCard = bankCard;
//            this._tmsServiceBus = tmsServiceBus;
//            this._serviceProvider = serviceProvider;

//            var configurationBuilder = new ConfigurationBuilder()
//                 .SetBasePath(appEnv.ApplicationBasePath)
//                .AddJsonFile($"{ConfigurationFileName}.json")
//                .AddJsonFile($"{ConfigurationFileName}.{env.EnvironmentName}.json", optional: true)
//                .AddEnvironmentVariables();

//            this.Configuration = configurationBuilder.Build();
//            this.DomainName = Configuration.GetSection("AppSettings")?["DomainName"] ?? "@site.com";

//            this._logger.LogInformation($"Starting TmsSyncOrderBackgroundWorker {InstanceCount++}");

//            this.Start();
//        }

//        public override void Start()
//        {
//            base.Start();
//        }

//        protected async override Task<bool> Process()
//        {
//            try
//            {
//                using (var serviceScope = this._serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
//                {
//                    using (var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
//                    {
//                        using (var userManager = serviceScope.ServiceProvider.GetService<ApplicationUserManager>())
//                        {
//                            var orders = (await this._tmsServiceBus.GetOrdersAsync())?.List?.ToList() ?? new List<Repositories.Models.Order>();
//                            foreach (var order in orders)
//                            {
//                                var line = this.AddOrUpdateTransportLinkage(order.TransportLinkage);
//                                order.TransportLinkage = null;
//                                order.TransportLinkageId = line.TransportLinkageId;
//                                //order.ContactChatId = $"{user.Id}:{order.ContactChatId}";
//                                dbContext.InsertOrUpdate(order);
//                                dbContext.SaveChanges();
//                                var user = await AddOrUpdateUserInfoAsync(order.ContactPhoneNumber, order.ContactName, null, false, true, new string[]
//                                {
//                                    ApplicationRole.Staff
//                                });
//                            }
//                        }
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                this._logger.LogError(ex.Message + Environment.NewLine + ex.StackTrace, ex);
//            }
//            await Task.Delay(TimeSpan.FromMinutes(1));
//            return await Task.FromResult(true);
//        }

//        private TransportLinkage AddOrUpdateTransportLinkage(TransportLinkage line)
//        {
//            using (var serviceScope = this._serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
//            {
//                using (var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
//                {
//                    var findEntity = dbContext.TransportLinkages.FirstOrDefault(x => x.Equals(line));
//                    if (findEntity == null)
//                    {
//                        dbContext.TransportLinkages.Add(line);
//                        dbContext.SaveChanges();
//                        return line;
//                    }
//                    return findEntity;
//                }
//            }
//        }

//        private async Task<ApplicationUser> AddOrUpdateUserInfoAsync(string driverPhone, string driverName, string carId, bool useCarIdAsKey = true, bool updateRealName = true, string[] roleNames = null)
//        {
//            try
//            {
//                using (var serviceScope = this._serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
//                {
//                    using (var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
//                    {
//                        using (var userManager = serviceScope.ServiceProvider.GetService<ApplicationUserManager>())
//                        {
//                            ApplicationUser user;
//                            if (useCarIdAsKey)
//                            {
//                                user = dbContext.Users.FirstOrDefault(x => x.CarId == carId);
//                            }
//                            else
//                            {
//                                user = dbContext.Users.FirstOrDefault(x => x.PhoneNumber == driverPhone);
//                            }
//                            if (user == null)
//                            {
//                                user = await ApplicationDbInitializer.CreateUserAsync(userManager, this._logger, driverPhone, driverName + $"@{this.DomainName}", driverPhone, roleNames ?? new string[]
//                                {
//                                    ApplicationRole.Driver
//                                });
//                                if (user == null)
//                                {
//                                    this._logger.LogError($"Failed to add user driverName={driverName}, driverPhone={driverPhone}.");
//                                }
//                                user.CarId = carId;
//                                dbContext.SaveChanges();
//                            }
//                            else
//                            {
//                                if (updateRealName)
//                                {
//                                    user.RealName = driverName;
//                                    dbContext.SaveChanges();
//                                }
//                            }
//                            return user;
//                        }
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                this._logger.LogError("Failed to add or update a user from EventBus.", ex);
//                throw;
//            }
//        }

//        private string AddOrUpdateCarInfo(string carCode, CarLength? carLength = null, CarriageType? carriageType = null, VehicleType? vehicleType = null)
//        {
//            try
//            {
//                using (var serviceScope = this._serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
//                {
//                    using (var dbContext = serviceScope.ServiceProvider.GetService<ApplicationDbContext>())
//                    {
//                        var car = dbContext.Cars.FirstOrDefault(x => x.Code == carCode);
//                        if (car == null)
//                        {
//                            car = new Car()
//                            {
//                                Code = carCode,
//                                Length = carLength ?? CarLength.None,
//                                CarriageType = carriageType ?? CarriageType.None,
//                                Type = vehicleType ?? VehicleType.None
//                            };
//                            dbContext.Cars.Add(car);
//                            dbContext.SaveChanges();
//                        }
//                        else
//                        {
//                            car.Length = carLength ?? car.Length;
//                            car.CarriageType = carriageType ?? car.CarriageType;
//                            car.Type = vehicleType ?? car.Type;
//                            dbContext.SaveChanges();
//                        }
//                        return car.CarId;
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
//                this._logger.LogError("Failed to add or update a car from EventBus.", ex);
//                throw;
//            }
//        }

//    }

//}